<template>
  <div>
    <div>纹理贴图</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  onMounted(() => {
    init();
  });

  function init() {
    const scene = new THREE.Scene();
    const width = 800;
    const height = 500;
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(500, 500, 500);
    camera.lookAt(scene.position);
    const render = new THREE.WebGLRenderer({
      //想把canvas画布上内容下载到本地，需要设置为true
      // preserveDrawingBuffer: true,
      // 设置对数深度缓冲区，优化深度冲突问题
      // logarithmicDepthBuffer: true,
    });
    render.setSize(width, height);
    // console.log(' webgl.value', webgl.value);

    webgl.value.appendChild(render.domElement);
    // document.body.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    // const pointLight = new THREE.PointLight(0xfff00f);
    // pointLight.position.set(0, 20, 300);
    // scene.add(pointLight);
    // const pointLightHelper = new THREE.PointLightHelper(pointLight, 20);
    // scene.add(pointLightHelper);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    //CircleGeometry的顶点UV坐标是按照圆形采样纹理贴图
    const geometrycir = new THREE.SphereGeometry(50, 32);
    const geometry = new THREE.PlaneGeometry(200, 100, 2, 2);
    //   const geometry = new THREE.SphereGeometry(60, 60, 60); //球体
    geometry.rotateY(Math.PI / 4);

    geometry.translate(10, 50, 10);
    //纹理贴图加载器TextureLoader
    const texLoader = new THREE.TextureLoader();
    // .load()方法加载图像，返回一个纹理对象Texture
    const texture = texLoader.load('/public/38.png');
    texture.colorSpace = THREE.SRGBColorSpace; //设置为SRGB颜色空间
    const material = new THREE.MeshLambertMaterial({
      // 设置纹理贴图：Texture对象作为材质map属性的属性值
      map: texture, //map表示材质的颜色贴图属性
      // side: THREE.DoubleSide,
    });
    const uvs = new Float32Array([0, 0, 0.5, 0, 0.5, 0.5, 0, 0.5]);
    console.log('uvs', uvs);

    // geometry.attributes.uv = new THREE.BufferAttribute(uvs, 2);

    const materialMesh = new THREE.Mesh(geometry, material);
    scene.add(materialMesh);
    const materCir = new THREE.Mesh(
      geometrycir,
      new THREE.MeshBasicMaterial({
        map: texture, //map表示材质的颜色贴图属性
        side: THREE.DoubleSide,
      }),
    );
    materCir.translateX(200);

    scene.add(materCir);
    console.log('uv', geometrycir.attributes.uv);

    function renderFun() {
      // console.log('asdfasdf');
      render.render(scene, camera);
      requestAnimationFrame(renderFun);
    }
    renderFun();
  }
</script>
